package admin

import (
	"invitation/internal/application"
	"invitation/internal/http/middleware"
	"invitation/internal/model"
	"invitation/internal/pojo/dto"

	"github.com/gofiber/fiber/v2"
)

func CreateTeacherEndpoint(application *application.Application) func(ctx *fiber.Ctx) error {
	return func(ctx *fiber.Ctx) error {
		teacherReq := ctx.Locals(middleware.LocalKeysTeacherCreateRequest).(*dto.FirstTimePayload)
		if teacherReq.Name == "" {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "name is required",
			})
		}
		if teacherReq.Desc == "" {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "desc is required",
			})
		}
		txCtx, err := application.RepoManager().BeginTx(ctx.Context())
		if err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		defer func() {
			if err != nil {
				application.RepoManager().RollbackTx(txCtx)
			} else {
				application.RepoManager().CommitTx(txCtx)
			}
		}()
		// 先创建一个临时对象获取ID
		tempInfo := &model.FirstTimeTeacherInfo{
			Name: teacherReq.Name,
			Desc: teacherReq.Desc,
		}
		id, err := application.RepoManager().FirstTimeTeacherInfoRepo().Create(tempInfo)
		if err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}

		if teacherReq.PostportUrl != "" {
			if err := application.RepoManager().FirstTimePostportRepo().Create(id, teacherReq.PostportUrl); err != nil {
				return ctx.Status(500).JSON(fiber.Map{
					"message": err.Error(),
				})
			}
		}
		return ctx.Status(200).JSON(fiber.Map{
			"message": "success",
		})
	}
}
